package com.jmm.api.service.impl.sms;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jmm.api.dao.sms.ApiSmsValidateMapper;
import com.jmm.api.dao.user.ApiOauthMapper;
import com.jmm.api.pojo.domain.sms.ApiSmsValidateDO;
import com.jmm.api.pojo.domain.user.ApiOauthDO;
import com.jmm.api.service.sms.ApiSmsValidateService;
import com.jmm.common.constant.AliDySmsTemplateCodeConstants;
import com.jmm.common.constant.RegConstants;
import com.jmm.common.exception.YogoException;
import com.jmm.common.type.EnumErrorCode;
import com.jmm.common.utils.AliDySmsUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


/**
 * The type Sms code service.
 *
 * @author Administrator
 */
@Service("apiSmsValidateService")
@Transactional
public class ApiSmsValidateServiceImpl extends ServiceImpl<ApiSmsValidateMapper,ApiSmsValidateDO> implements ApiSmsValidateService {

    /**
     * The Log.
     */
    Log log = LogFactory.get();
    @Autowired
    private ApiOauthMapper apiOauthMapper;
    /**
     * 获取注册验证码
     * @param phone
     */
    @Override
    public void getRegisterCode(Long phone) {
        log.info("获取注册验证码：{}",phone);
        getSmsCode4Null(phone);
    }

    /**
     * 获取忘记密码验证码
     * @param phone
     */
    @Override
    public void getForgetCode(Long phone){
        log.info("获取忘记密码验证码：{}",phone);
        getSmsCode4NotNull(phone);
    }

    /**
     * 获取登录验证码
     * @param phone
     */
    @Override
    public void getLoginCode(Long phone){
        log.info("获取登录验证码：{}",phone);
        getSmsCode4NotNull(phone);
    }

    /**
     * 获取更换手机号验证码
     * @param userId
     */
    @Override
    public void getChangePhoneCode(String userId) {
        if (StrUtil.isEmpty(userId)){
            throw new YogoException(EnumErrorCode.paramsFail.getCodeStr());
        }
        ApiOauthDO entity = new ApiOauthDO();
        entity.setOauthType(1);
        entity.setUserId(userId);
        ApiOauthDO apiOauthDO = apiOauthMapper.selectOne(new QueryWrapper<>(entity));
        String oauthId = apiOauthDO.getOauthId();
        log.info("获取更换手机号验证码：{}",oauthId);
        getSmsCode4NotNull(Long.parseLong(oauthId));
    }

    /**
     * 获取绑定新手机验证码
     *
     * @param phone
     */
    @Override
    public void getBandingPhoneCode(Long phone) {
        log.info("获取绑定新手机验证码：{}",phone);
        getSmsCode4Null(phone);
    }

    /**
     * 手机号存在时发送通用验证码
     * @param phone
     */
    private void getSmsCode4NotNull(Long phone){
        if(!ReUtil.isMatch(RegConstants.PHONE_REG, String.valueOf(phone))){
            log.info("手机号格式错误：{}",phone);
            throw new YogoException(EnumErrorCode.apiSmsPhoneNotMatch.getCodeStr());
        }
        //检测手机号是否已注册
        ApiOauthDO oathDo = new ApiOauthDO();
        oathDo.setOauthType(1);
        oathDo.setOauthId(String.valueOf(phone));
        ApiOauthDO apiOauthDO = apiOauthMapper.selectOne(new QueryWrapper<>(oathDo));
        if(apiOauthDO == null){
            log.info("该手机号未注册：{}",phone);
            throw new YogoException(EnumErrorCode.apiPhoneNotExist.getCodeStr());
        }
        String code = RandomUtil.randomNumbers(4);
        ApiSmsValidateDO smsDo = new ApiSmsValidateDO();
        smsDo.setPhone(phone);
        smsDo.setCode(code);
        smsDo.setUsed(0);
        smsDo.setExpirationTime(System.currentTimeMillis()+(5*60*1000));
        saveOrUpdate(smsDo);
        //执行发送短信
        AliDySmsUtils.sendSms(String.valueOf(phone), AliDySmsTemplateCodeConstants.SMS_53510049, MapUtil.of("pwdverification",code));
    }

    /**
     * 手机号不存在时发送通用验证码
     * @param phone
     */
    private void getSmsCode4Null(Long phone){
        if(!ReUtil.isMatch(RegConstants.PHONE_REG, String.valueOf(phone))){
            log.info("手机号格式错误：{}",phone);
            throw new YogoException(EnumErrorCode.apiSmsPhoneNotMatch.getCodeStr());
        }
        //检测手机号是否已注册
        ApiOauthDO oathDo = new ApiOauthDO();
        oathDo.setOauthType(1);
        oathDo.setOauthId(String.valueOf(phone));
        ApiOauthDO apiOauthDO = apiOauthMapper.selectOne(new QueryWrapper<>(oathDo));
        if(apiOauthDO != null){
            log.info("该手机号已被注册：{}",phone);
            throw new YogoException(EnumErrorCode.apiPhoneExist.getCodeStr());
        }
        String code = RandomUtil.randomNumbers(4);
        ApiSmsValidateDO smsDo = new ApiSmsValidateDO();
        smsDo.setPhone(phone);
        smsDo.setCode(code);
        smsDo.setExpirationTime(System.currentTimeMillis()+(5*60*1000));
        smsDo.setUsed(0);
        saveOrUpdate(smsDo);
        //执行发送短信
        AliDySmsUtils.sendSms(String.valueOf(phone), AliDySmsTemplateCodeConstants.SMS_53660076, MapUtil.of("regverification",code));
    }


}
